package com.swh.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.swh.entity.User;
import com.swh.utils.XBHashMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: swh
 * @Description:
 * @Date: 2020/11/23 11:59
 * @Version: 1.0
 */
public class BaseServlet extends HttpServlet {
    public HttpSession session;

    public User login;
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        request.setCharacterEncoding("UTF-8");

        session=request.getSession();

        login= (User) session.getAttribute("login");

        // http://localhost:8080/user/findALl ---> /user/findALl
        String uri = request.getRequestURI();

        // findAll
        uri = uri.substring(uri.lastIndexOf("/") + 1);

        System.out.println(this);

        Class targetClass = this.getClass();        // UserServlet.class

        try {
            // findAll
            Method method = targetClass.getMethod(uri, HttpServletRequest.class, HttpServletResponse.class);

            method.setAccessible(true);
            method.invoke(this, request, response);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public Map<String,String> getParam(HttpServletRequest request){

        Map<String, String[]> parameterMap = request.getParameterMap();

        Map<String, String> map=new XBHashMap();

        for(String key :parameterMap.keySet()){
            String[] values = parameterMap.get(key);

            map.put(key,values[0]);
        }
        return map;
    }

    /**
     * 对象转json方法
     * @return
     **/
    public void writeObjToString(HttpServletResponse response,Object obj){
        //图片上传用json
        response.setContentType("application/json;charset=utf8");

//        response.setContentType("text/html;charset=UTF-8");
        ObjectMapper om = new ObjectMapper();
        try {
            String strJson = om.writeValueAsString(obj);
            response.getWriter().write(strJson);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
